import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
// 路由规则配置
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/home/index.vue')
  },
  {
    path: '/category',
    name: 'category',
    component: () => import('@/views/category/index.vue')
  },
  {
    path: '/lcategoryDetail/:categoryId',
    name: 'categoryDetail',
    component: () => import('@/views/categoryDetail/index.vue'),
    props: true
  },
  {
    path: '/address',
    name: 'address',
    component: () => import('@/views/address/index.vue'),
    props: true,
    meta:{ requireAuth: true }
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('@/views/order/index.vue'),
    props: true,
    meta:{ requireAuth: true }
  },
  {
    path: '/order-confirm',
    name: 'order-confirm',
    component: () => import('@/views/orderConfirm/index.vue'),
    props: true,
    meta:{ requireAuth: true }
  },
  {
    path: '/orderDetail',
    name: 'orderDetail',
    component: () => import('@/views/orderDetail/index.vue'),
    props: true,
    meta:{ requireAuth: true }
  },
  {
    path: '/pay',
    name: 'pay',
    component: () => import('@/views/pay/index.vue'),
    meta:{ requireAuth: true }
  },
  {
    path: '/product/:productId',
    name: 'product',
    component: () => import('@/views/product/index.vue'),
    props: true
  },
  {
    path: '/comment/:productId',
    name: 'comment',
    component: () => import('@/views/comment/index.vue'),
    props: true
  },
  {
    path: '/recommend',
    name: 'recommend',
    component: () => import('@/views/recommend/index.vue')
  },
  {
    path: '/car',
    name: 'car',
    component: () => import('@/views/car/index.vue'),
    meta:{ requireAuth: true }
  },
  {
    path: '/search',
    name: 'search',
    component: () => import('@/views/search/index.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('@/views/user/index.vue'),
    meta:{ requireAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/views/notFound/index.vue')
  }
]

// 创建实例
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
// 设置导航守卫
router.beforeEach( to =>{
  // 无需登录的路由直接通过
  if (!to.meta.requireAuth) { return true }
  // 需要登录才能访问的路由 对其进行校验看vuex和本地是否存在token信息
  // 如果不存在跳转页面
  if (!store.state.user.token || !window.localStorage.getItem('USER_TOKEN')) {
    return {
      name: 'login',
      query: {
        redirect: to.fullPath
      }
    }
  }
})
// 导出实例
export default router
